package vehicle_model

import (
	"fmt"

	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/app"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/database"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/paginator"

	"github.com/gofiber/fiber/v2"
)

func Get(id uint64) (vehicleModel VehicleModel) {
	database.DB.Where("id", id).First(&vehicleModel)
	return
}

func GetBy(field, value string) (vehicleModel VehicleModel) {
	database.DB.Where("? = ?", field, value).First(&vehicleModel)
	return
}

func GetByName(value string) (vehicleModel VehicleModel) {
	database.DB.Where("name = ?", value).First(&vehicleModel)
	return
}

func All() (vehicleModels []VehicleModel) {
	database.DB.Order("id desc").Find(&vehicleModels)
	return
}

func GetByBrandId(brandId uint64) (vehicleModels []VehicleModel) {
	modelsModel := database.DB.Order("id desc")

	if brandId != 0 {
		fmt.Println(brandId)
		modelsModel.Where("brand_id = ?", brandId)
	}

	modelsModel.Find(&vehicleModels)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(VehicleModel{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

// Paginate 分页内容
func Paginate(c *fiber.Ctx, perPage int) (vehicleModels []VehicleModel, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(VehicleModel{}),
		&vehicleModels,
		app.V1URL(database.TableName(&VehicleModel{})),
		perPage,
	)
	return
}
